import useThemeStore from '@/store/theme.ts'
import {getDarkColor, getLightColor} from '@/utils/utils.ts'
import {onBeforeMount} from 'vue'
import {ElMessage} from 'element-plus'
import mittBus from '@/utils/mittBus.ts'

export const setTheme = () => {
	const themeStore = useThemeStore()
	const defaultPrimary = import.meta.env.VITE_DEFAULT_PRIMARY
	// 切换暗黑模式
	const switchDark = () => {
		const body = document.documentElement
		if (themeStore.isDark) body.setAttribute('class', 'dark')
		else body.setAttribute('class', '')
		changePrimary(themeStore.primary)
		mittBus.emit('setMapTheme', themeStore.isDark)
	}
	
	// 修改主题颜色
	const changePrimary = (val: string) => {
		if (!val) {
			val = defaultPrimary
			ElMessage({type: 'success', message: `主题颜色已重置为 ${defaultPrimary}`})
		}
		themeStore.setPrimary(val)
		// 为了兼容暗黑模式下主题颜色也正常，以下方法计算主题颜色 由深到浅 的具体颜色
		document.documentElement.style.setProperty('--el-color-primary', themeStore.primary)
		const lightColor: any = themeStore.isDark ? getLightColor(themeStore.primary, 0.2) : getDarkColor(themeStore.primary, 0.3)
		document.documentElement.style.setProperty('--el-color-primary-dark-2', lightColor)
		// 颜色加深或变浅
		for (let i = 1; i <= 9; i++) {
			const color: any = themeStore.isDark ? getDarkColor(themeStore.primary, i / 10) : getLightColor(themeStore.primary, i / 10)
			document.documentElement.style.setProperty(`--el-color-primary-light-${i}`, color)
		}
	}
	
	// 灰色和弱色切换
	const changeGreyOrWeak = (value: boolean, type: string) => {
		const body = document.body
		if (!value) {
			body.setAttribute('style', '')
			return
		}
		if (type === 'grey') body.setAttribute('style', 'filter: grayscale(1)')
		if (type === 'weak') body.setAttribute('style', 'filter: invert(80%)')
		const propName = type === 'grey' ? 'isWeak' : 'isGrey'
		themeStore.setWeakOrGrey(propName, false)
	}
	
	onBeforeMount(() => {
		switchDark()
		changePrimary(themeStore.primary)
		if (themeStore.isGrey) changeGreyOrWeak(true, 'grey')
		if (themeStore.isWeak) changeGreyOrWeak(true, 'weak')
	})
	
	return {
		switchDark,
		changePrimary,
		changeGreyOrWeak
	}
}
